package com.clwl.supervise.superviseapp.controller.risk;


import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.clwl.supervise.superviseapp.config.RepeatSubmit;
import com.clwl.supervise.superviseapp.entity.base.CommonSearchEntity;
import com.clwl.supervise.superviseapp.entity.base.TcCompany;
import com.clwl.supervise.superviseapp.entity.base.rectificationSituationData.RectificationSituationData;
import com.clwl.supervise.superviseapp.entity.result.ResultEntity;
import com.clwl.supervise.superviseapp.entity.risk.*;
import com.clwl.supervise.superviseapp.entity.risk.saveEntity.RiskDynamicVo;
import com.clwl.supervise.superviseapp.entity.risk.saveEntity.RiskStaticVo;
import com.clwl.supervise.superviseapp.service.risk.RiskManagerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 风险分级和等级评定功能
 */
@Slf4j
@RestController
@RequestMapping("riskManager")
public class RiskManagerController {


    @Resource
    private RiskManagerService riskManagerService;


    /**
     * 获取风险分级和等级评定表
     *
     * @param pageNum
     * @param pageSize
     * @param params
     * @return
     */
    @GetMapping("getList")
    public ResultEntity<IPage<Map<String, Object>>> getCompanyList(@RequestParam(required = true) Integer pageNum, @RequestParam(required = true) Integer pageSize, CommonSearchEntity params) {
        IPage<Map<String, Object>> pageList = riskManagerService.selectCompanyPage(pageNum, pageSize, params);
        return ResultEntity.success(pageList);
    }

    /**
     * 获取检查的时候页面信息
     *
     * @param companyId 企业id
     * @return
     */
    @RepeatSubmit
    @GetMapping("getStaticContentInfo")
    public ResultEntity<Map<String, Object>> getStaticContentInfo(Long companyId) {
        try {
            if (companyId == null) {
                return ResultEntity.error("请传递企业id");
            }
            Map<String, Object> superviseInfo = riskManagerService.getStaticContentInfo(companyId);
            return ResultEntity.success(superviseInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.error(e.getMessage());
        }
    }


    /**
     * 获取检查结果的内容
     *
     * @param checkId 检查结果id
     * @return
     */
    @RepeatSubmit
    @GetMapping("getStaticContentResultInfo")
    public ResultEntity<Map<String, Object>> getStaticContentResultInfo(Long staticScoringId) {
        try {
            if (staticScoringId == null) {
                return ResultEntity.error("请传递静态评分id");
            }
            Map<String, Object> superviseInfo = riskManagerService.getStaticContentResultInfo(staticScoringId);
            return ResultEntity.success(superviseInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.error(e.getMessage());
        }
    }

    /**
     * 保存检查门头照照片
     *
     * @param checkId 检查Id
     * @param file    门头照文件
     * @return
     */
    @RepeatSubmit(lockTime = 10)
    @PostMapping("uploadStaticCheckFile")
    public ResultEntity uploadStaticCheckFile(Long checkId, MultipartFile file) {
        try {
            JgStaticScoring check = riskManagerService.uploadStaticCheckFile(checkId, file);
            return ResultEntity.success(check);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.error("操作失败");
        }
    }

    /**
     * 保存告知单
     *
     * @param checkId    评分id
     * @param informFile 告知单
     * @return
     */
    @RepeatSubmit(lockTime = 10)
    @PostMapping("saveRiskStaticCheckInform")
    public ResultEntity saveRiskStaticCheckInform(Long checkId, String informFile) {
        try {
            String filePath = riskManagerService.saveCheckInform(checkId, informFile);
            return ResultEntity.success(filePath);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.error(e.getMessage());
        }
    }


    /**
     * 保存评分信息
     *
     * @param riskData    风险评分信息
     * @param temporarily 1临时 ；0正式保存
     * @return
     */
    @RepeatSubmit(lockTime = 10)
    @PostMapping("saveRiskStaticCheck")
    public ResultEntity saveRiskStaticCheck(String riskData, String temporarily) {
        try {

            log.info("riskData:{}", riskData);
            RiskStaticVo riskStaticVo = JSONObject.parseObject(riskData, RiskStaticVo.class);
            riskManagerService.saveRiskStaticCheck(riskStaticVo, temporarily);
            return ResultEntity.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.error(e.getMessage());
        }
    }

    /**
     * 查询沿用上一年静态评分信息
     *
     * @param checkId
     * @return
     */
    @GetMapping("getRiskStaticLastYearCheck")
    public ResultEntity<Map<String, Object>> getRiskStaticLastYearCheck(Long companyId) {
        try {
            Map<String, Object> riskStaticLastYearCheck = riskManagerService.getRiskStaticLastYearCheck(companyId);
            return ResultEntity.success(riskStaticLastYearCheck);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.error(e.getMessage());
        }
    }

    /**
     * 保存沿用上一年静态评分信息
     *
     * @param checkId
     * @return
     */
    @RepeatSubmit
    @PostMapping("saveRiskStaticLastYearCheck")
    public ResultEntity saveRiskStaticLastYearCheck(String checkId, Long scorePerson1Id, Long scorePerson2Id) {
        try {
            riskManagerService.saveRiskStaticLastYearCheck(checkId, scorePerson1Id, scorePerson2Id);
            return ResultEntity.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.error(e.getMessage());
        }
    }

//--------------------------------------------------------动态评分------------------------------------------------------

    /**
     * 获取动态评分检查页面信息
     *
     * @param companyId
     * @return
     */
    @RepeatSubmit
    @GetMapping("getDynamicContentInfo")
    public ResultEntity getDynamicContentInfo(Long companyId) {
        try {
            Map<String, Object> riskMap = riskManagerService.getDynamicContentInfo(companyId);
            riskMap.put("IS_LIABILITY", "0");
            return ResultEntity.success(riskMap);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.error(e.getMessage());
        }
    }

    /**
     * 保存检查门头照照片
     *
     * @param checkId 检查Id
     * @param file    门头照文件
     * @return
     */
    @RepeatSubmit(lockTime = 3)
    @PostMapping("uploadDynamicCheckFile")
    public ResultEntity uploadDynamicCheckFile(Long checkId, MultipartFile file) {
        try {
            JgDynamicScoring check = riskManagerService.uploadDynamicCheckFile(checkId, file);
            return ResultEntity.success(check);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.error("操作失败");
        }
    }

    /**
     * 保存告知单
     *
     * @param checkId    评分id
     * @param informFile 告知单
     * @return
     */
    @RepeatSubmit(lockTime = 10)
    @PostMapping("saveRiskDynamicCheckInform")
    public ResultEntity saveRiskDynamicCheckInform(Long checkId, String informFile) {
        try {
            JgDynamicScoring check = riskManagerService.saveRiskDynamicCheckInform(checkId, informFile);
            return ResultEntity.success(check);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.error(e.getMessage());
        }
    }

    /**
     * 查询结果表需要的数据
     *
     * @param checkId 日常检查表  JgDynamicScoring id
     * @return
     */
    @GetMapping("getRiskResultTable")
    public ResultEntity getRiskResultTable(Long checkId) {
        try {
            Map<String, Object> resultTable = riskManagerService.getRiskResultTable(checkId);
            return ResultEntity.success(resultTable);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.error("操作失败");
        }
    }


    /**
     * 上传结果记录的文件
     *
     * @param checkId 日常检查结果表id
     * @param imgFile 二进制文件流
     * @param type    1-要点表；2-记录表
     * @return
     */
    @RepeatSubmit
    @PostMapping("uploadResultRecord")
    public ResultEntity uploadResultRecord(Long checkId, @RequestPart(required = true, name = "imgFile") MultipartFile imgFile, String type
    ) {
        try {
            if (imgFile != null && StringUtils.isBlank(imgFile.getOriginalFilename())) {
                return ResultEntity.error("请上传文件");
            }
            String fileUrl = riskManagerService.uploadResultRecord(checkId, imgFile, type);
            if (StringUtils.isEmpty(fileUrl)) {
                return ResultEntity.error("上传失败");
            }
            return ResultEntity.success(fileUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.error("操作失败");
        }
    }

    /**
     * 保存动态检查信息
     *
     * @param riskData    检查页面的数据
     * @return
     */
    @PostMapping("saveRiskDynamicCheck")
    @RepeatSubmit(lockTime = 10)
    public ResultEntity saveRiskDynamicCheck(String riskData,  String liabilitySituationData) {
        try {
            RiskDynamicVo riskDunamicVo = JSONObject.parseObject(riskData, RiskDynamicVo.class);
            RectificationSituationData liabilitySituation = com.alibaba.fastjson.JSONObject.parseObject(liabilitySituationData, RectificationSituationData.class);
            riskManagerService.saveRiskDynamicCheck(riskDunamicVo,   liabilitySituation);
            return ResultEntity.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.error(e.getMessage());
        }
    }

    /**
     * 保存动态检查信息
     *
     * @param riskData    检查页面的数据
     * @return
     */
    @PostMapping("saveRiskDynamicCheckOver")
    @RepeatSubmit(lockTime = 10)
    public ResultEntity saveRiskDynamicCheckOver(String riskData,  String liabilitySituationData) {
        try { RiskDynamicVo riskDunamicVo = JSONObject.parseObject(riskData, RiskDynamicVo.class);
            RectificationSituationData liabilitySituation = com.alibaba.fastjson.JSONObject.parseObject(liabilitySituationData, RectificationSituationData.class);
            riskManagerService.saveRiskDynamicCheckOver(riskDunamicVo,liabilitySituation);
            return ResultEntity.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.error(e.getMessage());
        }
    }

    /**
     * 查询动态评分完成的订单
     * @return
     */
    @GetMapping("getRiskDynamicResultInfo")
    public ResultEntity getRiskDynamicResultInfo(Long dynamicScoringId) {
        try {
            Map<String, Object> result = riskManagerService.getCheckResultInfo(dynamicScoringId);
            return ResultEntity.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询检查完成的订单失败");
            return ResultEntity.error("操作失败");
        }
    }

    /**
     * 查询动态评分检查呢内容列表
     *
     * @param standardId 标准项id
     * @return
     */
    @GetMapping("getRiskDynamicContentList")
    public ResultEntity getRiskDynamicContentList(Long standardId) {
        try {
            List<JgDynamicContent> result = riskManagerService.getRiskDynamicContentList(standardId);
            return ResultEntity.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询检查完成的订单失败");
            return ResultEntity.error("操作失败");
        }
    }

    //---------------------------------------经营企业风险等级评定或生产企业初次评级------------------------------------------------------------------------------

    /**
     * 获取评定等级的基础信息和评分内容
     *
     * @param companyId 评定的时候会传递这个参数
     * @param riskLevelId 审核不通过的时候进来会传递这个参数
     * @return
     */
    @GetMapping("getRiskLevelInfo")
    public ResultEntity getRiskLevelInfo(Long companyId,Long riskLevelId) {
        try {
            if(riskLevelId == null) {
                try {
                    //校验评分完成情况
                    riskManagerService.checkScoreStatus(companyId);
                } catch (Exception e) {
                    return ResultEntity.error(e.getMessage());
                }
            }
            JgRiskLevel result = riskManagerService.getNoCheckRiskLevelInfo(companyId,riskLevelId);
            /* TcCompany tcCompany = riskManagerService.findCompanyById(companyId);
           if("spxs".equals(tcCompany.getSupProcess()) || "cyfw".equals(tcCompany.getSupProcess())){
                //食品经营
                if("1".equals(tcCompany.getIsTeshi()) || "1".equals(tcCompany.getIsXiaoyuan()) || "1".equals(tcCompany.getIsGongpi()) ){
                    //锁死为D级
                    String cause = "为";
                    if("1".equals(tcCompany.getIsTeshi())){
                        cause += "特殊食品，";
                    }
                    if("1".equals(tcCompany.getIsXiaoyuan())){
                        cause += "校园周边，";
                    }
                    if("1".equals(tcCompany.getIsGongpi())){
                        cause += "农批市场，";
                    }
                    result.setMessage("由于当前企业"+cause+"评级后最终的评分等级将固定为D级!");
                }
                if(tcCompany.getCompanyTypeId() == 5L && "1".equals(tcCompany.getIsShezuo())){
                    result.setMessage("由于当前企业为制售类食品摊贩设座小餐饮，评级后的等级如果低于B级，最终的评分将保存为B级!");
                }
            }*/
            return ResultEntity.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.error(e.getMessage());
        }
    }


    /**
     * 获取评定等级的基础信息和评分内容
     *
     * @param riskLevelId 等级评定id
     * @return
     */
    @GetMapping("getRiskLevelInfoResult")
    public ResultEntity getRiskLevelInfoResult(Long riskLevelId) {
        try {
            JgRiskLevel result = riskManagerService.getRiskLevelInfo(riskLevelId);
            return ResultEntity.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.error(e.getMessage());
        }
    }


    /**
     * 保存评级信息
     *
     * @param riskData    检查页面的数据
     * @param temporarily 是否临时 1-临时;0-非临时
     * @return
     */
    @RepeatSubmit(lockTime = 10)
    @PostMapping("saveRiskLevelInfo")
    public ResultEntity saveRiskLevelInfo(String riskData, String temporarily) {
        try {

            JgRiskLevel jgRiskLevel = JSONObject.parseObject(riskData, JgRiskLevel.class);
            String isShezuo = jgRiskLevel.getIsShezuo();
            System.out.println(isShezuo);
            Long companyId = jgRiskLevel.getCompanyId();
            try {
                //保存的时候也校验评分完成情况
                riskManagerService.checkScoreStatus(companyId);
            } catch (Exception e) {
                return ResultEntity.error(e.getMessage());
            }
            //获取企业是否为经营品种包含畜禽，水产品的食品销售者
            TcCompany tcCompany = riskManagerService.findCompanyById(companyId);
            boolean companyLevelStatus = false;
            if ("spxs".equals(tcCompany.getSupProcess()) && tcCompany.getCompanyTypeId() == 2L) {
                JgSpjyxk spjyxkEntity = riskManagerService.findAdsJgSpjyxkByLisenceNo(tcCompany.getLicense());
                if (spjyxkEntity != null && (spjyxkEntity.getZsncppl().contains("猪肉") || spjyxkEntity.getZsncppl().contains("牛羊肉") || spjyxkEntity.getZsncppl().contains("禽类及其产品") || spjyxkEntity.getZsncppl().contains("水产品"))) {
                    companyLevelStatus = true;
                }
            }
            if ("spxs".equals(tcCompany.getSupProcess()) && tcCompany.getCompanyTypeId() == 6L) {
                JgSpzc spzcEntity = riskManagerService.findAdsJgSpzcByLisenceNo(tcCompany.getLicense());
                if (spzcEntity != null && (spzcEntity.getZcplgc().contains("猪肉") || spzcEntity.getZcplgc().contains("牛羊肉") || spzcEntity.getZcplgc().contains("禽类及其产品") || spzcEntity.getZcplgc().contains("水产品"))) {
                    companyLevelStatus = true;
                }
            }
            JgRiskLevel resultRiskLevel = riskManagerService.saveRiskLevelInfo(jgRiskLevel, temporarily, tcCompany, companyLevelStatus);
            return ResultEntity.success(resultRiskLevel);
        } catch (Exception e) {
            e.printStackTrace();
            if (StringUtils.equals("分数不在等级匹配数据范围，请确认后再进行操作", e.getMessage())) {
                return ResultEntity.error(e.getMessage());
            }
            return ResultEntity.error("保存失败");
        }
    }

    /**
     * 评分审核
     *
     * @param riskId         风险评分id
     * @param examineResult  评分结果
     * @param examineOpinion 评分意见
     * @return
     */
    @RepeatSubmit(lockTime = 10)
    @PostMapping("saveRiskLevelExamine")
    public ResultEntity saveRiskLevelExamine(Long riskId, String examineResult, String examineOpinion) {
        try {
            riskManagerService.saveRiskLevelExamine(riskId, examineResult, examineOpinion);
            return ResultEntity.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.error(e.getMessage());
        }
    }

    /**
     * 通过检查的内容获取风险xinxi
     *
     * @param checkContentId
     * @return
     */
    @GetMapping("getRiskTypeByCheckContent")
    public ResultEntity getRiskTypeByCheckContent(Long checkContentId) {
        try {
            List<Map<String, Object>> riskType = riskManagerService.getRiskTypeByCheckContent(checkContentId);
            return ResultEntity.success(riskType);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.error(e.getMessage());
        }
    }


    /**
     * 风险等级评级确认表
     *
     * @param checkId
     * @return
     */
    @GetMapping("getRiskConfirmTable")
    public ResultEntity getRiskConfirmTable(Long checkId) {
        try {
            Map<String, Object> riskTable = riskManagerService.getRiskConfirmTable(checkId);
            return ResultEntity.success(riskTable);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.error("获取失败");
        }
    }

    /**
     * 保存风险等级评级确认表
     *
     * @param checkId
     * @return
     */
    @RepeatSubmit(lockTime = 10)
    @PostMapping("updateRiskConfirmTable")
    public ResultEntity updateRiskConfirmTable(Long checkId, MultipartFile imgFile) {
        try {
            riskManagerService.updateRiskConfirmTable(checkId, imgFile);
            return ResultEntity.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.error("获取失败");
        }
    }

}
